package com.example.managemyself.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * OpenWeatherMap天气助手类
 * 使用免费的OpenWeatherMap API获取天气信息
 */
public class OpenWeatherHelper {
    
    private static final String TAG = "OpenWeatherHelper";
    
    // OpenWeatherMap API配置
    private static final String BASE_URL = "https://api.openweathermap.org/data/2.5/weather";
    private static final String API_KEY = "37c3e6912770beb285f2b5358714d5ad"; // OpenWeather API密钥
    
    private static OpenWeatherHelper instance;
    private OkHttpClient httpClient;
    private ExecutorService executorService;
    private Handler mainHandler;
    
    public static synchronized OpenWeatherHelper getInstance() {
        if (instance == null) {
            instance = new OpenWeatherHelper();
        }
        return instance;
    }
    
    private OpenWeatherHelper() {
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                .build();
        executorService = Executors.newFixedThreadPool(3);
        mainHandler = new Handler(Looper.getMainLooper());
    }
    
    public void initialize(Context context) {
        Log.i(TAG, "OpenWeatherHelper initialized");
    }
    
    /**
     * 根据经纬度获取当前天气
     */
    public void getCurrentWeatherByLocation(double latitude, double longitude, WeatherCallback callback) {
        // 检查线程池状态，如果已关闭则重新创建
        if (executorService.isShutdown() || executorService.isTerminated()) {
            executorService = Executors.newFixedThreadPool(3);
        }
        
        try {
            executorService.execute(() -> {
                try {
                    String url = BASE_URL + "?lat=" + latitude + "&lon=" + longitude 
                            + "&appid=" + API_KEY + "&units=metric&lang=zh_cn";
                    
                    Request request = new Request.Builder()
                            .url(url)
                            .get()
                            .build();
                    
                    Response response = httpClient.newCall(request).execute();
                    if (response.isSuccessful() && response.body() != null) {
                        String responseBody = response.body().string();
                        JSONObject jsonObject = new JSONObject(responseBody);
                        
                        WeatherInfo weatherInfo = parseWeatherData(jsonObject);
                        mainHandler.post(() -> callback.onWeatherSuccess(weatherInfo));
                    } else {
                        mainHandler.post(() -> callback.onError("网络请求失败"));
                    }
                } catch (IOException | JSONException e) {
                    Log.e(TAG, "天气获取异常", e);
                    mainHandler.post(() -> callback.onError("天气获取异常: " + e.getMessage()));
                }
            });
        } catch (RejectedExecutionException e) {
            Log.e(TAG, "线程池已关闭，任务被拒绝", e);
            mainHandler.post(() -> callback.onError("服务暂时不可用，请稍后重试"));
        }
    }
    
    /**
     * 根据城市名获取当前天气
     */
    public void getCurrentWeatherByCity(String cityName, WeatherCallback callback) {
        // 检查线程池状态，如果已关闭则重新创建
        if (executorService.isShutdown() || executorService.isTerminated()) {
            executorService = Executors.newFixedThreadPool(3);
        }
        
        try {
            executorService.execute(() -> {
                try {
                    String url = BASE_URL + "?q=" + cityName + "&appid=" + API_KEY + "&units=metric&lang=zh_cn";
                    
                    Request request = new Request.Builder()
                            .url(url)
                            .get()
                            .build();
                    
                    Response response = httpClient.newCall(request).execute();
                    if (response.isSuccessful() && response.body() != null) {
                        String responseBody = response.body().string();
                        JSONObject jsonObject = new JSONObject(responseBody);
                        
                        WeatherInfo weatherInfo = parseWeatherData(jsonObject);
                        mainHandler.post(() -> callback.onWeatherSuccess(weatherInfo));
                    } else {
                        mainHandler.post(() -> callback.onError("网络请求失败"));
                    }
                } catch (IOException | JSONException e) {
                    Log.e(TAG, "天气获取异常", e);
                    mainHandler.post(() -> callback.onError("天气获取异常: " + e.getMessage()));
                }
            });
        } catch (RejectedExecutionException e) {
            Log.e(TAG, "线程池已关闭，任务被拒绝", e);
            mainHandler.post(() -> callback.onError("服务暂时不可用，请稍后重试"));
        }
    }
    
    /**
     * 解析天气数据
     */
    private WeatherInfo parseWeatherData(JSONObject jsonObject) throws JSONException {
        WeatherInfo weatherInfo = new WeatherInfo();
        
        // 基本信息
        weatherInfo.cityName = jsonObject.getString("name");
        
        // 主要天气信息
        JSONObject main = jsonObject.getJSONObject("main");
        weatherInfo.temperature = String.valueOf(Math.round(main.getDouble("temp")));
        weatherInfo.feelsLike = String.valueOf(Math.round(main.getDouble("feels_like")));
        weatherInfo.humidity = String.valueOf(main.getInt("humidity"));
        weatherInfo.pressure = String.valueOf(main.getInt("pressure"));
        
        // 天气描述
        if (jsonObject.has("weather") && jsonObject.getJSONArray("weather").length() > 0) {
            JSONObject weather = jsonObject.getJSONArray("weather").getJSONObject(0);
            weatherInfo.weatherText = weather.getString("description");
            weatherInfo.iconCode = weather.getString("icon");
        }
        
        // 风力信息
        if (jsonObject.has("wind")) {
            JSONObject wind = jsonObject.getJSONObject("wind");
            weatherInfo.windSpeed = String.valueOf(Math.round(wind.getDouble("speed") * 3.6)); // m/s to km/h
            if (wind.has("deg")) {
                weatherInfo.windDir = getWindDirection(wind.getInt("deg"));
            }
        }
        
        // 能见度
        if (jsonObject.has("visibility")) {
            weatherInfo.visibility = String.valueOf(jsonObject.getInt("visibility") / 1000); // m to km
        }
        
        return weatherInfo;
    }
    
    /**
     * 根据角度获取风向
     */
    private String getWindDirection(int degree) {
        String[] directions = {"北", "东北", "东", "东南", "南", "西南", "西", "西北"};
        int index = (int) Math.round(degree / 45.0) % 8;
        return directions[index];
    }
    
    /**
     * 天气信息数据类
     */
    public static class WeatherInfo {
        public String cityName;         // 城市名称
        public String temperature;      // 温度
        public String weatherText;      // 天气描述
        public String iconCode;         // 天气图标代码
        public String windDir;          // 风向
        public String windSpeed;        // 风速
        public String humidity;         // 湿度
        public String pressure;         // 气压
        public String visibility;       // 能见度
        public String feelsLike;        // 体感温度
        
        @Override
        public String toString() {
            return weatherText + " " + temperature + "°C";
        }
        
        public String getDetailedInfo() {
            return String.format("天气: %s\n温度: %s°C\n体感: %s°C\n湿度: %s%%\n风向: %s\n风速: %s km/h",
                    weatherText, temperature, feelsLike, humidity, windDir, windSpeed);
        }
    }
    
    /**
     * 天气回调接口
     */
    public interface WeatherCallback {
        void onWeatherSuccess(WeatherInfo weatherInfo);
        void onError(String error);
    }
    
    /**
     * 检查服务是否可用
     */
    public boolean isServiceAvailable() {
        return executorService != null && !executorService.isShutdown() && !executorService.isTerminated();
    }
    
    /**
     * 释放资源
     */
    public void release() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
} 